<script setup lang="ts">
	import {getDictOptions} from "@/api/dict";

	/**
	 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
	 */
	defineOptions({
		name: "AuditConfig",
		inheritAttrs: false,
	});
	import {ElLoading, UploadFile} from "element-plus";
	import 'element-plus/theme-chalk/el-loading.css'
	import {
		getAuditColumnPage,
		downloadTemplateApi,
		importAuditColumn,
		exportAuditColumn
	} from "@/api/auditConfig";

	import {AuditColumnQuery} from "@/api/auditConfig/types";
	import axios from "axios";
	import {exportBillColumn} from "@/api/tableConfig";

	const queryFormRef = ref(ElForm); // 查询表单

	const loading = ref(false);
	const ids = ref([]);
	const total = ref(0);
	const activeTab = ref()
	const selectTab = ref()
	const storeDictList = ref<OptionType[]>();

	const queryParams = reactive<AuditColumnQuery>({
		pageNum: 1,
		pageSize: 20,
	});
	const auditColumnList = ref<[]>();

	const importDialog = reactive<DialogOption>({
		title: "标准账单配置导入",
		visible: false,
	});

	/**
	 * 导入选择的部门ID
	 */
	const excelFile = ref<File>();
	const excelFilelist = ref<File[]>([]);


	/**
	 * 查询
	 */
	function handleQuery(tabName?: string) {
		queryParams.platform = tabName
		loading.value = true;
		getAuditColumnPage(queryParams)
				.then(({data}) => {
					auditColumnList.value = data.list;
					total.value = data.total;
				})
				.finally(() => {
					loading.value = false;
				});
	}

	/** 重置查询 */
	function resetQuery() {
		queryParams.pageNum = 1;
		handleQuery(selectTab.value);
	}


	/** 下载导入模板 */
	function downloadTemplate() {
		axios.get('file/核销报表导入模板.xlsx', {
			responseType: 'blob',
		}).then(response => {
			const url = window.URL.createObjectURL(new Blob([response.data]));
			const link = document.createElement('a')
			let fname = '核销报表导入模板.xlsx'
			link.href = url
			link.setAttribute('download', fname)
			document.body.appendChild(link)
			link.click()
		})
	}

	/** 打开导入弹窗 */
	async function openImportDialog() {
		importDialog.visible = true;
	}

	/**
	 * 获取字典类型的数据项
	 *
	 * @param typeCode 字典类型编码
	 */
	function getDictOptionList() {
		getDictOptions('platform').then((response) => {
			storeDictList.value = response.data;
			activeTab.value = storeDictList.value[0].value
			selectTab.value = storeDictList.value[0].label
			handleQuery(selectTab.value); // 初始化标准账单配置列表数据
		});
	}

	/**
	 * Excel文件change事件
	 *
	 * @param file
	 */
	function handleExcelChange(file: UploadFile) {
	  if (file.size !== undefined) {
		  if (file.size > 20*1024*1024) {
			  ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			  return false
		  }
	  }
		if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
			ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
			excelFile.value = undefined;
			excelFilelist.value = [];
			return false;
		}
		excelFile.value = file.raw;
	}

	/** 导入用户提交 */
	function handleUserImport() {
		if (!excelFile.value) {
			ElMessage.warning("上传Excel文件不能为空");
			return false;
		}
		const importLoading = ElLoading.service({
			lock: true,
			text: '导入中...',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		importAuditColumn(excelFile.value).then((response) => {
			importLoading.close()
			ElMessage.success(response.data);
			closeImportDialog();
			resetQuery();
		})
	}

	/**  关闭导入弹窗 */
	function closeImportDialog() {
		importDialog.visible = false;
		excelFile.value = undefined;
		excelFilelist.value = [];
	}


	function tabClick(e?: any) {
		selectTab.value = e.props.label
		handleQuery(selectTab.value)
	}

	/** 导出核销账单配置 */
	function handleAuditColumnExport() {
		exportAuditColumn().then((response: any) => {
			const blob = new Blob([response.data], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
			});
			const a = document.createElement("a");
			const href = window.URL.createObjectURL(blob); // 下载的链接
			a.href = href;
			a.download = decodeURI(
					response.headers["content-disposition"].split(";")[1].split("=")[1]
			); // 获取后台设置的文件名称
			document.body.appendChild(a);
			a.click(); // 点击导出
			document.body.removeChild(a); // 下载完成移除元素
			window.URL.revokeObjectURL(href); // 释放掉blob对象
		});
	}

	onMounted(() => {
		getDictOptionList()

	});
</script>

<template>
	<div class="app-container">
		<el-row :gutter="20">

			<el-col>
				<!--        <div class="search-container">-->
				<!--          <el-form ref="queryFormRef" :model="queryParams" :inline="true">-->
				<!--            <el-form-item label="关键字" prop="keywords">-->
				<!--              <el-input-->
				<!--                v-model="queryParams.keywords"-->
				<!--                placeholder="用户名/昵称/手机号"-->
				<!--                clearable-->
				<!--                style="width: 200px"-->
				<!--                @keyup.enter="handleQuery"-->
				<!--              />-->
				<!--            </el-form-item>-->

				<!--            <el-form-item>-->
				<!--              <el-button type="primary" @click="handleQuery"-->
				<!--                ><i-ep-search />搜索</el-button-->
				<!--              >-->
				<!--              <el-button @click="resetQuery">-->
				<!--                <i-ep-refresh />-->
				<!--                重置</el-button-->
				<!--              >-->
				<!--            </el-form-item>-->
				<!--          </el-form>-->
				<!--        </div>-->

				<el-card shadow="never">
					<template #header>
						<div class="flex justify-between">
							<div>
								<el-button class="ml-3" @click="openImportDialog"
								><template #icon><i-ep-top /></template>导入</el-button
								>
								<el-button class="ml-3" @click="handleAuditColumnExport"
								><template #icon><i-ep-download /></template>导出</el-button
								>
							</div>
						</div>
					</template>

					<el-tabs type="border-card" v-model="activeTab" @tab-click="tabClick">
						<el-tab-pane v-for="store of storeDictList" :label="store.label" :name="store.value" >
							<el-table
									size="small"
									:header-row-style="{color: 'dimgray'}"
									v-loading="loading"
									:data="auditColumnList"
									border
							>
								<el-table-column
										label="来源报表"
										align="center" show-overflow-tooltip
										prop="sourceTable"
										width="100"
								/>
								<el-table-column
										label="关联字段"
										align="center" show-overflow-tooltip
										prop="linkColumn"
										width="100"
								/>
								<el-table-column
										label="账单日期"
										align="center" show-overflow-tooltip
										prop="billDate"
										width="100"
								/>
								<el-table-column
										label="发退货时间"
										align="center" show-overflow-tooltip
										prop="sendReturnTime"
										width="180"
								/>
								<el-table-column
										label="下单时间"
										width="180"
										align="center" show-overflow-tooltip
										prop="orderTime"
								/>
								<el-table-column
										label="对账系统平台编码"
										width="160"
										align="center" show-overflow-tooltip
										prop="secordSourceCode"
								/>

								<el-table-column
										label="对账系统平台名称"
										width="160"
										align="center" show-overflow-tooltip
										prop="secordSourceName"
								/>
								<el-table-column
										label="内部系统电商平台编码"
										align="center" show-overflow-tooltip
										prop="innerShopCode"
										width="180"
								></el-table-column>
								<el-table-column
										label="内部系统电商平台名称"
										align="center" show-overflow-tooltip
										prop="innerShopName"
										width="180"
								></el-table-column>
								<el-table-column
										label="对账平台店铺编码"
										align="center" show-overflow-tooltip
										prop="dzPlatformStoreCode"
										width="160"
								/>

								<el-table-column
										label="内部系统店铺编码"
										width="160"
										align="center" show-overflow-tooltip
										prop="shopCode"
								/>
								<el-table-column
										label="内部系统店铺名称"
										align="center" show-overflow-tooltip
										prop="shopName"
										width="160"
								/>

								<el-table-column
										label="自有平台主订单号"
										align="center" show-overflow-tooltip
										prop="onwerPreformNo"
										width="180"
								></el-table-column>
								<el-table-column
										label="原始主订单号"
										align="center" show-overflow-tooltip
										prop="sourcePreformMainNo"
										width="180"
								></el-table-column>
								<el-table-column
										label="原始子订单号"
										align="center" show-overflow-tooltip
										prop="sourcePreformSubNo"
										width="180"
								></el-table-column>
								<el-table-column
										label="PO单号"
										align="center" show-overflow-tooltip
										prop="poNo"
										width="180"
								></el-table-column>
<!--								<el-table-column-->
<!--										label="渠道编码"-->
<!--										align="center" show-overflow-tooltip-->
<!--										prop="channelCode"-->
<!--										width="180"-->
<!--								></el-table-column>-->
<!--								<el-table-column-->
<!--										label="渠道"-->
<!--										align="center" show-overflow-tooltip-->
<!--										prop="channel"-->
<!--										width="180"-->
<!--								></el-table-column>-->

								<el-table-column
										label="电商平台店铺编码"
										align="center" show-overflow-tooltip
										prop="thirdSourceCode"
										width="180"
								></el-table-column>
								<el-table-column
										label="电商平台店铺名称"
										align="center" show-overflow-tooltip
										prop="thirdSourceName"
										width="180"
								></el-table-column>
								<el-table-column
										label="入账主体"
										align="center" show-overflow-tooltip
										prop="receiveCompany"
										width="180"
								></el-table-column>
								<el-table-column
										label="电商平台登录账号"
										align="center" show-overflow-tooltip
										prop="shopAccount"
										width="180"
								></el-table-column>
								<el-table-column
										label="财务系统店铺编码"
										align="center" show-overflow-tooltip
										prop="billSysStore"
										width="180"
								></el-table-column>
								<el-table-column
										label="财务系统店铺名称"
										align="center" show-overflow-tooltip
										prop="billSysStoreName"
										width="180"
								></el-table-column>
								<el-table-column
										label="商品单价"
										align="center" show-overflow-tooltip
										prop="price"
										width="180"
								></el-table-column>
								<el-table-column
										label="发货数量"
										align="center" show-overflow-tooltip
										prop="qty"
										width="180"
								></el-table-column>
								<el-table-column
										label="发货金额"
										align="center" show-overflow-tooltip
										prop="sendAmount"
										width="180"
								></el-table-column>
								<el-table-column
										label="退货数量"
										align="center" show-overflow-tooltip
										width="180"
								>
									<template #default="scope">{{scope.row.returnQty === 0 ? '' : scope.row.returnQty}}</template>
								</el-table-column>
								<el-table-column
										label="退货金额"
										align="center" show-overflow-tooltip
										width="180"
								>
									<template #default="scope">{{scope.row.returnAmount === 0 ? '' : scope.row.returnAmount}}</template>
								</el-table-column>
								<el-table-column
										label="收款日期"
										align="center" show-overflow-tooltip
										prop="receiveDate"
										width="180"
								></el-table-column>
								<el-table-column
										label="收款金额"
										align="center" show-overflow-tooltip
										prop="receiveAmount"
										width="180"
								></el-table-column>
								<el-table-column
										label="退款日期"
										align="center" show-overflow-tooltip
										prop="refundDate"
										width="180"
								></el-table-column>
								<el-table-column
										label="退款金额"
										align="center" show-overflow-tooltip
										width="180"
								>
									<template #default="scope">{{scope.row.refundAmount === 0 ? '' : scope.row.refundAmount}}</template>
								</el-table-column>
								<el-table-column
										label="保证金退款金额"
										align="center" show-overflow-tooltip
										width="180"
								>
									<template #default="scope">{{scope.row.depositAmount === 0 ? '' : scope.row.depositAmount}}</template>
								</el-table-column>
								<el-table-column
										label="自系统调账日期"
										align="center" show-overflow-tooltip
										prop="systemReconciliationDate"
										width="180"
								></el-table-column>
								<el-table-column
										label="自系统调账数量"
										align="center" show-overflow-tooltip
										prop="systemReconciliationQty"
										width="180"
								></el-table-column>
								<el-table-column
										label="自系统调账金额"
										align="center" show-overflow-tooltip
										prop="systemReconciliationAmount"
										width="180"
								></el-table-column>
								<el-table-column
										label="财务调账日期"
										align="center" show-overflow-tooltip
										prop="reconciliationDate"
										width="180"
								></el-table-column>
								<el-table-column
										label="财务调账数量"
										align="center" show-overflow-tooltip
										prop="reconciliationQty"
										width="180"
								></el-table-column>
								<el-table-column
										label="财务调账金额"
										align="center" show-overflow-tooltip
										prop="reconciliationAmount"
										width="180"
								></el-table-column>
								<el-table-column
										label="差异数量"
										align="center" show-overflow-tooltip
										prop="differenceQty"
										width="180"
								></el-table-column>
								<el-table-column
										label="应收账款余额"
										align="center" show-overflow-tooltip
										prop="receiveBillAmount"
										width="180"
								></el-table-column>
								<el-table-column
										label="业务日期"
										align="center" show-overflow-tooltip
										prop="businessDate"
										width="180"
								></el-table-column>
								<el-table-column
										label="是否核销"
										align="center" show-overflow-tooltip
										prop="audit"
										width="180"
								></el-table-column>
								<el-table-column
										label="核销结果分类"
										align="center" show-overflow-tooltip
										prop="mainTypeName"
										width="180"
								></el-table-column>
								<el-table-column
										label="订单核销细类名称"
										align="center" show-overflow-tooltip
										prop="auditDetailName"
										width="180"
								></el-table-column>
								<el-table-column
										label="异常售后未提报金额"
										align="center" show-overflow-tooltip
										prop="serviceBillAmount"
										width="180"
								>
									<template #default="scope">
										{{scope.row.serviceBillAmount === 0 ? '' : scope.row.serviceBillAmount}}
									</template>
								</el-table-column>
								<el-table-column
										label="是否推送"
										align="center" show-overflow-tooltip
										prop="push"
										width="180"
								></el-table-column>
								<el-table-column
										label="核销状态"
										align="center" show-overflow-tooltip
										prop="auditStatus"
										width="180"
								></el-table-column>
							</el-table>
							<pagination
									v-if="total > 0"
									v-model:total="total"
									v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize"
									@pagination="handleQuery(selectTab)"
							/>
						</el-tab-pane>
					</el-tabs>
				</el-card>
			</el-col>
		</el-row>

		<!-- 导入弹窗 -->
		<el-dialog
				v-model="importDialog.visible"
				:title="importDialog.title"
				width="600px"
				append-to-body
				@close="closeImportDialog"
		>
			<el-form label-width="80px">

				<el-form-item label="Excel">
					<el-upload
							class="upload-demo"
							action=""
							drag
							:auto-upload="false"
							accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
							:file-list="excelFilelist"
							:on-change="handleExcelChange"
							:limit="1"
					>
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled/>
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">xls/xlsx files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleUserImport">确 定</el-button>
					<el-button @click="closeImportDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
